<?php
/**
 *+-------公共基类--------+
 *+-------------------------------------------------+
 *+-------------------------------------------------+
 *+-@author susy.liang <liangling@ilongyuan.com.cn>-+
 *+-------------------------------------------------+
 */
namespace Api\Controller;

use Api\Event\CacheEvent;
use Think\Controller;
use Think\Hook;
use Api\Event\UserAuthEvent;
use Think\Log;
use Common\Util\RSA;

class PublicController extends Controller {

	static $API_ERROR;
	/**
	*用户的昵称
	*/
	protected $nickname = '';


	public function _empty() {
	}
	/**
	 *成员变量的初始化
	 */
	protected function _initialize() {
		$param = [
			'action' => strtolower('Api/' . CONTROLLER_NAME . '/' . ACTION_NAME),
		];
		Hook::listen('api_init', $param);

		$Redis = CacheEvent::instance(0);
		load_config($Redis);
		unset($Redis);
		$baseEvent = A('Api/Base', 'Event');
		self::$API_ERROR = $baseEvent::$API_ERROR;
		$query = IS_POST ? file_get_contents("php://input") : http_build_query(I(''));
		if (IS_POST){
			$method = 'POST';
			$this->rsaDecode();
		}elseif (IS_PUT) {
			$method = 'PUT';
		}elseif (IS_GET) {
			$method = 'GET';
		}elseif (IS_DELETE) {
			$method = 'DELETE';
		}
		// print_r(I('param.'));
		// $this->getRequest();
		\Think\Log::record("METHOD: {$method} ,API: " . $param['action'] . ' REQUEST: ' . $query, 'DEBUG');
	}

	public function getRequest()
	{
		$sign_type = I('sign_type');
		if (IS_POST && strtoupper($sign_type) == 'RSA'){
			$RSA = new RSA(C('RSA_PUBLIC_KEY'), C('RSA_PRIVATE_KEY'));
			// $content = file_get_contents("php://input");
			$content = I('sign');
			$request = $RSA->privateDecrypt($content)->toJson();
			if (!$request) {
				return $this->error(self::$API_ERROR['SIGN'], 'sign error');
			}
			$_POST = $request;
		}
	}


	protected function checkLogin()
	{
		$token = I('request.appToken', '', 'strip_tags,trim');
		$uid = $this->getUid($token);
		if(!$uid)
			$this->ajaxReturn(array('data'=>null, 'info'=>'用户未登录', 'code'=>self::$API_ERROR['UNLOGIN']));
		// $uid = 9;#TODO 测试
		if (!defined('UID'))
		{
			define('UID', (int)$uid );
		}
		$this->nickname = $nickname = get_nickname($uid);
		#TODO 测试
		// $nickname = 'xcx';
		if(empty($nickname) && strtolower(ACTION_NAME) != 'setnickname')
			$this->ajaxReturn(array('data'=>null, 'code'=>self::$API_ERROR['NO_NICKNAME'], 'info'=>'未设置昵称'));
		
		$param = [
			'uid'     => $uid,
			'action'  => strtolower(CONTROLLER_NAME .'/'.ACTION_NAME), 
			'fail'    => function(){
				$this->error(self::$API_ERROR['VISIT_OFTEN'], 'visit too often');
 			}
		];
		Hook::listen('user_auth_pass', $param);
	}

	protected function checkAuth($action)
	{
		$user = event('User')->info(UID);
		if (!UserAuthEvent::check($action, $user)){
			$this->error(self::$API_ERROR['DENY'], '操作等级不足');
		}
	}

	// 错误返回
	protected function error($code, $info, $extend = '') {
		$data['code'] = $code;
		$data['info'] = $info;
		$data['data'] = $extend ? $extend : '';
		$this->ajaxReturn($data);
	}

	protected function ajaxReturn($data, $type = '') {
		if (I('debug')) {
			C('SHOW_PAGE_TRACE', true);
			trace($data, 'response', 'DEBUG');
			return $this->show('debug');
		}
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Headers: X-Requested-With');
		parent::ajaxReturn($data, $type);
	}

	// 正确返回
	protected function success($info, $extend = '', $ajax = false) {

		$data['code'] = self::$API_ERROR['SUCCESS'];
		$data['info'] = $info;
		$data['data'] = $extend ? $extend : '';
		$this->ajaxReturn($data);
	}

	protected function list_success($list = [], $total = false) {
		$res = [
			'count' => count($list),
			'lists' => $list ?: [],
		];
		$total !== false && $res['total'] = $total;
		return $this->success('', $res);
	}

	protected function login_error() {
		return $this->error(self::$API_ERROR['UNLOGIN'], '用户未登录', null);
	}

	protected function param_error() {
		$this->error(self::$API_ERROR['PARAM'], '参数错误');
	}

	protected function sign_error() {
		$this->error(self::$API_ERROR['SIGN'], '签名错误');
	}

	// 数据格式化 只保留需要的数据
	protected function field_filter($data, $filter_map) {
		if (!$data) {
			return;
		}
		foreach ($data as $key => $value) {
			if (!in_array($key, $filter_map)) {
				unset($data[$key]);
			} else if (!isset($value)) {
				$data[$key] = '';
			}
		}
		return $data;
	}

	/**
	 *获取用户id
	 */
	protected function getUid($appToken = '') {
		// 修改可为空情况
		if (!$appToken) {
			return 0;
		}
		static $uid = null;
		if ($uid === null) {
			$redis = CacheEvent::instance(1);
			$key = "IMBA.USER.TOKEN.{$appToken}";
			// $uid = $redis->get($key);
			// \Think\Log::record("FROM redis has token {$appToken} get uid {$res}", "DEBUG");
			if (!$uid) {
				$map = array(
					'status' => 1,
					'app_token' => trim($appToken),
				);
				$res = service('Token')->where($map)->find();
				$uid = $res ? $res['uid'] : 0;
				if ($uid) {
					$redis->setex($key, 30, $res);
					// \Think\Log::record("set redis has token set uid {$uid}", "DEBUG");
				}
			}
		}
		return $uid ? $uid : 0;
	}

	/**
	 * 将数据库获取的video数据得到detai并格式化lists
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */

	protected function lists_format($videos, $filter_map = array('id', 'title', 'type', 'thumb', 'pre_uri', 'uri', 'dpi_levels', 'time', 'detail', 'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags', 'action', 'icons', 'reward_users', 'reward_times', 'reward_total', 'dpi_height', 'dpi_width')) {
		$item = array();
		if (!$videos) {
			return $item;
		}
		static $uid = null;
		if ($uid == null) {
			$uid = $this->getUid(I('appToken'));
		}

		$filter_game_map = array(
			'id', 'name', 'pic', 'cover', 'is_scribe',
		);
		$vEvent = A('Api/Video', 'Event');

		$service = D('Common/Video', 'Service');
		$videos = array_map('intval', $videos);
		$where['id'] = array('in', $videos);
		$res = $service->where($where)->select();
		foreach ($res as $value) {
			$vEvent::$STATIC['ovideo'][$value['id']] = $value;
		}

		foreach ($videos as $video_id) {
			$video = $vEvent->detail($video_id, $uid);
			if ($video) {
				$video = field_filter($video, $filter_map);
				$video['type'] = intval($video['type']);
				empty($video['tags']) && $video['tags'] = array();
				empty($video['icons']) && $video['icons'] = array();
				$video['game'] && $video['game'] = field_filter($video['game'], $filter_game_map);
				$item[] = $video;
			}
		}
		return $item;
	}

	// 过滤字段 只接受此字段内容
	protected function requestFilter($fields = []) {
		$data = I('param.');
		if (!$fields) {
			return $data;
		}

		foreach ($fields as $key) {
			isset($data[$key]) && $res[$key] = $data[$key];
		}
		Log::record("[DEBUG]-:".json_encode($res), 'DEBUG');
		return $res;
	}

	// 将视频按照视频/比赛分类返回列表
	protected function formatMVideos($item = []) {
		if (!$item) {
			return [];
		}

		$data = [];
		foreach ($item as $key => $value) {
			$data[] = array(
				'title' => $value['title'],
				'thumb' => $value['thumb'],
				'type' => $value['type'] ? $value['type'] : 0,
				'data' => $value,
			);
		}
		return $data;
	}

	protected function checkSign($param, $sign) {
		if (array_key_exists('sign', $param)) {
			unset($param['sign']);
		}
		ksort($param);

		$str = urldecode(http_build_query($param)) . C('SIGN_SECRET');
		if (strtolower($sign) !== md5($str)) {
			return $this->sign_error();
		}

	}

	protected function rsaDecode() {
		if (I('_sign_type') == 'rsa' && I('sign')){
			$RSA = new RSA(C('RSA_PUBLIC_KEY'), C('RSA_PRIVATE_KEY'));
	    	$request = $RSA->privateDecrypt(I('sign'))->toJson();
	    	if(!$request){
	    		return $this->sign_error();
	    	}

	    	$_POST = $_GET = $_REQUEST = $_REQUEST ? array_merge($_REQUEST, $request) : $request;
		}
	}

}